<script setup lang="ts">
import {computed, ref, defineEmits, nextTick} from "vue";
import type {RouterType} from "@/type/router-type.ts";
import {saveRouter} from "@/api/router-api.ts";
import {RowOptionEnum} from "@/type/table-type.ts";
import MLabel from "@/views/compontents/label/m-label.vue";
import RouterForm from "@/views/compontents/router-form.vue";
import ParamsForm from "@/views/compontents/params-form.vue";
import SqlForm from "@/views/compontents/sql-form.vue";
import type {SqlType} from "@/type/sql-type.ts";
import type {ParamGroupType} from "@/type/paramType.ts";
import {getParamGroupById, saveBatchParams} from "@/api/param-api.ts";
import {getSqlById, saveSql} from "@/api/sql-api.ts";

const visible = ref<boolean>(false)

const showDialog = () => {
  visible.value = true
}
const hideDialog = () => {
  visible.value = false
}

const routerFormObj = ref<RouterType>({})
const sqlFormObj = ref<SqlType>({})
const paramGroupObj = ref<ParamGroupType>({
  moyuSqlParamList: []
})
const emits = defineEmits(['close'])
const loading = ref<boolean>(false)

// 保存路由
const saveRouterHandler = async () => {
  try {
    loading.value = true
    let paramGroupId = ''
    if (routerFormObj.value.isRequest) {
      const res = await saveBatchParams(paramGroupObj.value)
      paramGroupId = res.data.paramGroupId
      const sqlRes = await saveSql(sqlFormObj.value)
      sqlFormObj.value = sqlRes.data
    }
    routerFormObj.value.paramGroupId = paramGroupId
    routerFormObj.value.sqlId = sqlFormObj.value.sqlId
    saveRouter(routerFormObj.value).then(() => {
      hideDialog()
    }).finally(() => {
      emits('close')
      loading.value = false
    })

  } catch (e) {
    console.error(e)
    loading.value = false
  }
}

// 操作信息
const formOption = ref<RowOptionEnum>(RowOptionEnum.ADD)
const enableEdit = computed(() => {
  return formOption.value !== RowOptionEnum.DETAIL
})

/**
 * 初始化路由数据
 * @param routerData 路由数据
 * @param option
 */
const initRouterData = (option: RowOptionEnum, routerData: RouterType | undefined) => {
  formOption.value = option
  routerFormObj.value = {} as RouterType
  sqlFormObj.value = {}
  paramGroupObj.value = {
    moyuSqlParamList: []
  }
  if (formOption.value === RowOptionEnum.ADD) {
    routerFormObj.value.parentId = routerData?.routerId
  } else if (formOption.value === RowOptionEnum.UPDATE) {
    routerFormObj.value = routerData as RouterType
    getSqlAndParamsHandler()
  } else if (formOption.value === RowOptionEnum.DETAIL) {
    routerFormObj.value = routerData as RouterType
    getSqlAndParamsHandler()
  }
}

const getSqlAndParamsHandler = () => {
  nextTick(() => {
    if (!routerFormObj.value.isRequest) {
      return
    }
    sqlFormObj.value = {}
    getSqlById(routerFormObj.value.sqlId as string).then(res => {
      sqlFormObj.value = res.data
    })
    paramGroupObj.value = {
      moyuSqlParamList: []
    }
    getParamGroupById(routerFormObj.value.paramGroupId as string).then(res => {
      paramGroupObj.value = res.data
    }).catch(() => {
      paramGroupObj.value = {
        moyuSqlParamList: []
      }
    })
  })
}

// 弹窗标题
const titleMap: { [any: string]: string } = {
  [RowOptionEnum.ADD]: '新增路由',
  [RowOptionEnum.UPDATE]: '更新路由',
  [RowOptionEnum.DETAIL]: '路由信息',
}

defineExpose({
  // 显示对话框
  showDialog,
  // 隐藏对话框
  hideDialog,
  // 初始化路由数据
  initRouterData,
})
</script>

<template>
  <div>
    <el-dialog v-if="visible"
               v-model="visible"
               :fullscreen="routerFormObj.isRequest"
               :title="titleMap[formOption]"
               :close-on-click-modal="false"
               :class="{'router-option-dialog':routerFormObj.isRequest}"
    >
      <template #default>
        <el-row :gutter="24">
          <el-col :span="routerFormObj.isRequest? 12 : 24">
            <m-label
                v-if="routerFormObj.isRequest"
                title="1、路由信息"
            />
            <router-form
                ref="routerFormRef"
                v-model="routerFormObj"
                :enableEdit="enableEdit"
                :collapse="routerFormObj.isRequest"
            />
            <m-label
                v-if="routerFormObj.isRequest"
                title="3、SQL参数信息"
            />
            <params-form
                ref="paramsFormRef"
                v-if="routerFormObj.isRequest"
                v-model="paramGroupObj"
            />
          </el-col>
          <el-col v-if="routerFormObj.isRequest" :span="12">
            <m-label title="2、SQL信息"/>
            <sql-form
                ref="sqlFormRef"
                v-model="sqlFormObj"
            />
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <el-button @click="hideDialog">取消</el-button>
        <el-button v-if="enableEdit"
                   type="primary"
                   :loading="loading"
                   @click="saveRouterHandler">保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.router-option-dialog .el-dialog__body) {
  height: calc(100vh - 120px);
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
